package com.adcc.loadsheet.billing.security;

import com.adcc.aoc.devLib.common.codec.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 用户登录认证器
 * Created by zhaoml on 2020-04-01.
 */
@Component
public class BillingUserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    BillingUserDetailesService billingUserDetailesService;

    // 通过用户名，密码的比对，完成真正的登录操作
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取登录用户信息
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        //获取密码
        String password = Base64.decodeString((String) token.getCredentials());
        //获取用户名
        String username = Base64.decodeString(token.getName());

        BillingUserDetails billingUserDetails = null;
        // 本地化校验用户名
        //本地用户验证
        billingUserDetailesService.checkLocalUserAndLock(password, username);
        //加载用户详细信息
        billingUserDetails = (BillingUserDetails) billingUserDetailesService.loadUserByUsername(username);
        return new UsernamePasswordAuthenticationToken(billingUserDetails, token.getCredentials(), billingUserDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}